package com.example.tang.zhayan.fragment;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.tang.zhayan.BaseApp;
import com.example.tang.zhayan.R;
import com.example.tang.zhayan.adapter.PopupwindowAdapter;
import com.example.tang.zhayan.adapter.WorksBodyAdapter;
import com.example.tang.zhayan.bean.BaseWorksBody;
import com.example.tang.zhayan.bean.BaseWorksHead;
import com.example.tang.zhayan.bean.DbBuyDetail;
import com.example.tang.zhayan.bean.WorksBodyItem;
import com.example.tang.zhayan.bean.WorksBodyList;
import com.example.tang.zhayan.bean.WorksHeadSecondMenu;
import com.example.tang.zhayan.constant.PathConstant;
import com.example.tang.zhayan.ui.BuyDetailsActivity;
import com.example.tang.zhayan.ui.ShopBagActivity;
import com.example.tang.zhayan.utils.EventUtils;
import com.example.tang.zhayan.utils.IntentUtils;
import com.example.tang.zhayan.utils.PopupwindowUtils;
import com.example.tang.zhayan.utils.ResultParamsUtils;
import com.example.tang.zhayan.utils.WindowsUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tang on 2015/12/14.
 */
@ContentView(R.layout.fragment_works)
public class WorksFragment extends BaseFragment implements View.OnClickListener {
    @ViewInject(R.id.img_works_searchType)
    private ImageView imgSearchType;
    @ViewInject(R.id.img_works_search)
    private ImageView imgSearch;
    @ViewInject(R.id.ptr_works_listview)
    private PullToRefreshListView ptrListView;
    @ViewInject(R.id.ll_works_price)
    private LinearLayout llPrice;
    @ViewInject(R.id.ll_works_populitary)
    private LinearLayout llPopulitary;
    @ViewInject(R.id.ll_works_discount)
    private LinearLayout llDiscount;
    @ViewInject(R.id.img_works_bag)
    private ImageView imgBag;
    @ViewInject(R.id.tv_works_num)
    private TextView textNum;

    private PopupWindow popupWindowMenu;
    private PopupWindow popupWindowChildMenu;
    private PopupWindow popupSearchWindow;
    private PopupwindowAdapter adapter;
    private PopupwindowAdapter adapterChild;
    private Map<String, String> map;
    private int pageNO = 1;


    private String id = "";
    //默认的数据集合
    private List<WorksBodyItem> listBody;
    //按照价格等分类的数据集合
    private List<WorksBodyItem> listPrice;
    //主菜单数据集合
    private List<String> listMenu;
    private List<String> listChildMenu;
    private List<String> listChildId;
    private List<List<WorksHeadSecondMenu>> lisSecondMenu;
    private WorksBodyAdapter worksAdapter;
    private int type = 0;
    //正在加载的弹出框
    private ProgressDialog dialog;

    /**
     * 单例模式
     *
     * @return
     */
    public static WorksFragment newInstance() {
        WorksFragment fragment = new WorksFragment();
        return fragment;
    }

    /**
     * 初始化控件 或者 数据
     * 比 initData() 方法先执行
     */
    @Override
    protected void initView() {
        super.initView();
        EventBus.getDefault().register(this);
        //每次进来的时候查询数据库是否有商品
        EventUtils.setGoodsNum(textNum);
        showDialog();
        addListener();
    }

    @Subscriber(tag = "buy")
    public void getTotalString(String str) {
        if (!str.equals("")) {
            try {
                List<DbBuyDetail> all = BaseApp.getApp().getDb().findAll(DbBuyDetail.class);
                if (all.size() == 0) {
                    textNum.setVisibility(View.GONE);
                } else {
                    textNum.setVisibility(View.VISIBLE);
                    textNum.setText((all.size()) + "");
                }
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 取消注册EventBus
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 初始化数据加载弹出框
     */
    public void showDialog() {
        dialog = new ProgressDialog(getActivity());
        dialog.setMessage(getActivity().getString(R.string.stringIsLoading));
    }

    private void addListener() {
        llPrice.setOnClickListener(this);
        llPopulitary.setOnClickListener(this);
        llDiscount.setOnClickListener(this);
        imgSearch.setOnClickListener(this);
        imgBag.setOnClickListener(this);
        imgSearchType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getMenuPopupWindow(v);
            }
        });
    }


    public void addSixData(String id) {
        map.clear();
        map.put("id", id);
        map.put("pageSize", "10");
        map.put("pageNo", pageNO + "");
        x.http().post(ResultParamsUtils.getIDParams(PathConstant.HOMEPAGE_SIX_DATA, map), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                BaseWorksBody baseWorksBody = JSON.parseObject(s, BaseWorksBody.class);
                listBody.addAll(baseWorksBody.getData().getList());
                worksAdapter.notifyDataSetChanged();
                ptrListView.onRefreshComplete();
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
            }

            @Override
            public void onCancelled(CancelledException e) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    /**
     * 加载主体界面的数据
     */
    public void addData() {
        initMap();
        x.http().post(ResultParamsUtils.getIDParams(PathConstant.WORKS_BODY, map), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                BaseWorksBody baseWorksBody = JSON.parseObject(s, BaseWorksBody.class);
                listBody.addAll(baseWorksBody.getData().getList());
                worksAdapter.notifyDataSetChanged();
                ptrListView.onRefreshComplete();
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
            }

            @Override
            public void onCancelled(CancelledException e) {
            }

            @Override
            public void onFinished() {
            }
        });
    }


    /**
     * 刷新数据
     */
    @Subscriber(tag = "init")
    public void initTypeData(String position) {
        if (!position.equals("")) {
            addSixData(position);
        }
    }

    /**
     * 初始化控件 或者 数据
     */
    @Override
    protected void initData() {
        super.initData();
        initList();
        initMap();
        addData();
        //初始化适配器
        worksAdapter = new WorksBodyAdapter(getActivity(), listBody);
        //绑定适配器
        ptrListView.setAdapter(worksAdapter);
        //数据刷新
        ptrListView.setMode(PullToRefreshListView.Mode.BOTH);
        ptrListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                addData();
                if (type != 0) {
                    getTypeData(type);
                }
                worksAdapter.notifyDataSetChanged();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageNO++;
                addData();
                if (type != 0) {
                    getTypeData(type);
                }
                worksAdapter.notifyDataSetChanged();
            }
        });

        //PullToRefreshListView点击事件
        clickItem();


    }


    /**
     * PullToRefresh的item点击事件
     */
    private void clickItem() {
        ptrListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), BuyDetailsActivity.class);
                if (type == 1) {
                    intent.putExtra("id", listPrice.get(position - 1).getId());
                    intent.putExtra("memberId", listPrice.get(position - 1).getStylist_id());
                } else if (type == 2) {
                    intent.putExtra("id", listPrice.get(position - 1).getId());
                    intent.putExtra("memberId", listPrice.get(position - 1).getStylist_id());
                } else if (type == 3) {
                    intent.putExtra("id", listPrice.get(position - 1).getId());
                    intent.putExtra("memberId", listPrice.get(position - 1).getStylist_id());
                } else {
                    intent.putExtra("id", listBody.get(position - 1).getId());
                    intent.putExtra("memberId", listBody.get(position - 1).getStylist_id());
                }
                startActivity(intent);
            }
        });

    }

    /**
     * 初始化List
     */
    public void initList() {
        listBody = new ArrayList<>();
        listPrice = new ArrayList<>();
        listChildMenu = new ArrayList<>();
        listMenu = new ArrayList<>();
        lisSecondMenu = new ArrayList<>();
        listChildId = new ArrayList<>();
    }


    /**
     * 初始化map
     */
    public void initMap() {
        map = new HashMap<>();
        if (!TextUtils.isEmpty(id)) {
            map.put("id", id);
        }
        map.put("pageSize", "10");
        map.put("pageNo", pageNO + "");
    }


    /**
     * 添加Popupwindow获取搜索界面弹出框
     */
    private void getSearchPopupWindow(View v) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.activity_search, null);
        EditText textName = (EditText) view.findViewById(R.id.et_search);
        ImageView imgBack = (ImageView) view.findViewById(R.id.iv_search_back);
        ImageView imgShop = (ImageView) view.findViewById(R.id.iv_search_shop);
        Button btnDesigner = (Button) view.findViewById(R.id.btn_search_deisgner);
        Button btnClothes = (Button) view.findViewById(R.id.btn_search_clothes);


        final AbsListView.LayoutParams params = new AbsListView.LayoutParams(new WindowsUtils(getActivity())
                .getScreenWidth(), new WindowsUtils(getActivity()).getScreenHeight());
        view.setLayoutParams(params);
        popupSearchWindow = new PopupWindow(view, new WindowsUtils(getActivity())
                .getScreenWidth(), new WindowsUtils(getActivity()).getScreenHeight());
        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupSearchWindow.dismiss();
            }
        });
        popupSearchWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
        popupSearchWindow.setOutsideTouchable(true);


        popupSearchWindow.setAnimationStyle(R.style.searchpopwindow_anim_style);
        //在底部显示Popupwindow
        popupSearchWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
    }


    /**
     * 子菜单弹出框
     */
    public void getChilMenuWindow(View v, int position, List<List<WorksHeadSecondMenu>> listSecond) {
        listChildMenu.clear();
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_child_item, null);
        //设置弹出框的宽度和高度
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(200, AbsListView.LayoutParams.WRAP_CONTENT);
        contentView.setLayoutParams(params);
        //初始化弹出框里的ListView
        ListView listView = (ListView) contentView.findViewById(R.id.lv_child_popupWindow);
        //初始化弹出框里面的adapter
        listView.setDividerHeight(0);
        adapterChild = new PopupwindowAdapter(getActivity(), listChildMenu);
        listView.setAdapter(adapterChild);
        for (int j = 0; j < lisSecondMenu.get(position).size(); j++) {
            listChildMenu.add(lisSecondMenu.get(position).get(j).getName());
            listChildId.add(lisSecondMenu.get(position).get(j).getId());
            adapterChild.notifyDataSetChanged();
            adapter.notifyDataSetChanged();
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                dialog.show();
                getChildMenuData(listChildId.get(position));
            }
        });


        popupWindowChildMenu = new PopupWindow(contentView, 100, ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置Popupwindow上的控件可以点击
        popupWindowChildMenu.setFocusable(true);
        popupWindowChildMenu.setWidth(110);
        popupWindowChildMenu.setAnimationStyle(R.style.mymenupopwindow_anim_style);
        popupWindowChildMenu.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.mediumseagreen)));
        popupWindowChildMenu.setOutsideTouchable(true);
        popupWindowChildMenu.showAtLocation(v, Gravity.TOP | Gravity.LEFT, 110, 110);
    }


    /**
     * 弹出框   菜单  PopupWindow
     */
    public void getMenuPopupWindow(final View v) {
        listMenu.clear();
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_item, null);
        //设置弹出框的宽度和高度
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(200, AbsListView.LayoutParams.WRAP_CONTENT);
        contentView.setLayoutParams(params);
        //初始化弹出框里的ListView
        ListView listView = (ListView) contentView.findViewById(R.id.lv_popupWindow);
        //初始化弹出框里面的adapter
        adapter = new PopupwindowAdapter(getActivity(), listMenu);
        listView.setDividerHeight(0);
        listView.setAdapter(adapter);
        //请求菜单数据
        getMenuData(adapter, listView, v);
        popupWindowMenu = new PopupWindow(contentView, 100, ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置Popupwindow上的控件可以点击
        popupWindowMenu.setFocusable(true);
        popupWindowMenu.setAnimationStyle(R.style.mypopwindow_anim_style);
        popupWindowMenu.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.mediumseagreen)));
        popupWindowMenu.setOutsideTouchable(true);
        popupWindowMenu.setWidth(110);
        popupWindowMenu.showAtLocation(v, Gravity.TOP | Gravity.LEFT, 0, 110);
    }


    /**
     * 改变数据
     *
     * @param num
     */
    public void changeTypeData(int num) {
        getTypeData(num);
        listPrice.clear();
        type = num;
        pageNO = 1;
    }

    /**
     * 控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_works_price:
                //显示数据加载
                dialog.show();
                changeTypeData(1);
                break;
            case R.id.ll_works_populitary:
                dialog.show();
                changeTypeData(2);
                break;
            case R.id.ll_works_discount:
                dialog.show();
                changeTypeData(3);
                break;
            case R.id.img_works_search:
                View view = LayoutInflater.from(context).inflate(R.layout.activity_search, null);
                popupSearchWindow = new PopupWindow(view, new WindowsUtils(context)
                        .getScreenWidth(), new WindowsUtils(context).getScreenHeight());
                PopupwindowUtils.getSearchPopupWindow(v, view, getActivity(), popupSearchWindow);
                break;
            case R.id.img_works_bag:
                IntentUtils.toShopBag(getActivity());
                break;
        }
    }

    /**
     * 价格\人气\折扣数据
     */
    public void getTypeData(int type) {
        map.clear();
        map.put("order", "0");
        map.put("type", type + "");
        map.put("pageSize", "10");
        map.put("pageNo", pageNO + "");
        x.http().post(ResultParamsUtils.getIDParams(PathConstant.WORKS_PRICE_PRODUCTS, map), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                BaseWorksBody baseWorksBody = JSON.parseObject(s, BaseWorksBody.class);
                listPrice.addAll(baseWorksBody.getData().getList());
                worksAdapter.notifyDataSetChanged();
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
            }

            @Override
            public void onCancelled(CancelledException e) {
            }

            @Override
            public void onFinished() {
            }
        });
        worksAdapter = new WorksBodyAdapter(getActivity(), listPrice);
        ptrListView.setAdapter(worksAdapter);
    }

    /**
     * 得到子菜单的数据
     */
    public void getChildMenuData(String position) {
        map.clear();
        listPrice.clear();
        map.put("pageSize", "10");
        map.put("order", "0");
        map.put("itemClass", position + "");
        map.put("type", type + "");
        map.put("pageNo", pageNO + "");
        x.http().post(ResultParamsUtils.getIDParams(PathConstant.WORKS_MENU_DETAILS, map), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                BaseWorksBody baseWorksBody = JSON.parseObject(s, BaseWorksBody.class);
                listPrice.addAll(baseWorksBody.getData().getList());
                worksAdapter.notifyDataSetChanged();
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
            }

            @Override
            public void onCancelled(CancelledException e) {
            }

            @Override
            public void onFinished() {
            }
        });
        worksAdapter = new WorksBodyAdapter(getActivity(), listPrice);
        ptrListView.setAdapter(worksAdapter);
    }

    /**
     * 得到主菜单数据
     *
     * @return
     */
    public void getMenuData(final PopupwindowAdapter adapter, final ListView listView, final View v) {
        map.clear();
        x.http().post(ResultParamsUtils.getIDParams(PathConstant.WORKS_MENU, map), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                BaseWorksHead baseWorksHead = JSON.parseObject(s, BaseWorksHead.class);
                listMenu.add("全部");
                for (int i = 0; i < baseWorksHead.getData().getList().size(); i++) {
                    listMenu.add(baseWorksHead.getData().getList().get(i).getName());
                    lisSecondMenu.add(baseWorksHead.getData().getList().get(i).getList());
                }
                //listview的点击事件
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (position == 0) {
                            changeTypeData(type);
                            dialog.show();
                        } else {
                            getChilMenuWindow(v, position - 1, lisSecondMenu);
                        }
                    }
                });
                adapter.notifyDataSetChanged();
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
            }

            @Override
            public void onCancelled(CancelledException e) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

}
